package com.itheima.controller;

import com.itheima.domain.Collection2;
import com.itheima.domain.FilePojo;
import com.itheima.domain.Question;
import com.itheima.domain.User;
import com.itheima.service.CollectionService;
import com.itheima.service.QuestionService;
import com.itheima.service.UserService;
import com.itheima.until.Code;
import com.itheima.until.Encryptor;

import com.itheima.until.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Controller
@RequestMapping("/users")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private CollectionService collectionService;
    @Autowired
    private QuestionService questionService;

    //去往登录页面
    @RequestMapping("/loginPage")
    public String loginPage(){
        return "login";
    }
    //去往注册界面
    @RequestMapping("/registerPage")
    public String registerPage(){
        return "register";
    }

    //登录
    @ResponseBody
    @RequestMapping("/login")
    public Result UserLogin(String loginname,String password,HttpSession session) {
        Integer identity = 1;
        if(userService.getByloginname(loginname).getIdentity() == 0) {
            return new Result(104,null,"该账号已被禁用!请联系管理员");
        }

        User oldUser = userService.getByloginname1(loginname,identity);
//        User oldUser = userService.getByloginname(loginname);

//        User oldUser = userService.getByloginname("aaa");
//        System.out.println(oldUser);
        if (oldUser == null) {
            return new Result(103,null,"用户名不存在");
            //账号错误
        }
        if (Encryptor.validate(password,oldUser.getPassword())){
            session.setAttribute("user",oldUser);
            return new Result(101, null);
//            return "101";
        }else {            //密码错误
            return new Result(102,null,"密码错误");
//            return "102";
        }
    }
    @ResponseBody
    @RequestMapping("/admin")
    public String adminLogin(String loginname,String password,Integer identity,HttpSession session) {
        if(userService.getByloginname(loginname).getIdentity() == 0) {
            return "104";
        }

        User oldUser = userService.getByloginname1(loginname,identity);
//        User oldUser = userService.getByloginname(loginname);

//        User oldUser = userService.getByloginname("aaa");
        System.out.println(oldUser);
        if (oldUser == null) {
//            return new Result(103,null,"用户名不存在");
            return "103";
            //账号错误
        }
        if (Encryptor.validate(password,oldUser.getPassword())){
            session.setAttribute("user",oldUser);


//            return new Result(101, null, "null");
            return "101";
        }else {            //密码错误

//            return new Result(102,null,"密码错误");
            return "102";
        }
    }

    //注册
    @ResponseBody
    @RequestMapping("/register")
    public String UserRegister(User user){
//        检验账号是否存在
        User byloginname = userService.getByloginname(user.getLoginname());
        if(byloginname != null){
            return "false";
        }

        String encrypt = Encryptor.encrypt(user.getPassword());
        user.setPassword(encrypt);
        user.setAvatar("res/images/uer.jpg");
        user.setCreatetime(new Date());
        user.setIdentity(1);
        user.setNickname("浦江用户"+ System.currentTimeMillis());
        userService.save(user);
        return "success";
    }

    //退出登录
    @RequestMapping("/logout")
    public String logout(HttpSession session){
//        System.out.println("session = " + session.getAttribute("user"));
        session.invalidate();

        return "redirect:/index";
    }

    @ResponseBody
    @RequestMapping("/avatarUp")
    public Result avatar(@RequestParam("file") MultipartFile file, HttpSession session) throws IOException {
        if(file == null){
            return new Result(201,null,"请不要上传空的文件");

        }

            //原始文件名
            String originalFilename = file.getOriginalFilename();

            //构造唯一文件名
            int index = originalFilename.lastIndexOf(".");
            String exname = originalFilename.substring(index);
            String newFilename = UUID.randomUUID().toString() + exname;

            String dir = session.getServletContext().getRealPath("/res/images/avatar");
            String address = dir+"/"+newFilename;

            file.transferTo((new File(address)));
            User user = (User) session.getAttribute("user");
            user.setAvatar("res/images/avatar/"+ newFilename);
            userService.update(user);

            return new Result(200,"res/images/avatar/"+ newFilename);

    }

    @ResponseBody
    @RequestMapping("/collect")
    public Result collect(Integer qid, HttpSession session){
        User user = (User) session.getAttribute("user");
        if(user == null){
            return new Result(201,null,"您尚未登陆");
        }
        Collection2 collection2 = new Collection2();
        collection2.setQid(qid);
        collection2.setUid(user.getUid());
        if(collectionService.getById(collection2.getQid(),collection2.getUid()) != null){
            return new Result(201, null, "帖子已经收藏");
        }else {
            boolean flag = collectionService.save(collection2);
            return new Result(200, null,"收藏成功");
        }
    }

    @ResponseBody
    @RequestMapping("/cancel")
    public Result cancel(Integer qid, HttpSession session){
        User user = (User) session.getAttribute("user");
        if(user == null){
            return new Result(201,null,"您尚未登陆");
        }
        Collection2 collection2 = new Collection2();
        collection2.setQid(qid);
        collection2.setUid(user.getUid());
        Collection2 collection = collectionService.getById(collection2.getQid(),collection2.getUid());
        if(collection == null){
            return new Result(201, null, "您还尚未收藏");
        }else {
            boolean flag = collectionService.delete(collection2);
            return new Result(200, null,"取消收藏成功");
        }
    }

    @RequestMapping("/myCollection")
    @ResponseBody
    public Result myCollection(Integer uid){
        List<Collection2> byUid = collectionService.getByUid(uid);

        List<Question> questions = new ArrayList<>();
        for (Collection2 collection: byUid) {
            Integer qid = collection.getQid();
            Question question = questionService.getById(qid);
            questions.add(question);
        }

        return new Result(200,questions);
    }
    @RequestMapping("/myQues")
    @ResponseBody
    public Result myQues(Integer uid){
        List<Question> questions = questionService.getByUid(uid);

        return new Result(200,questions);
    }

    @RequestMapping("/homeUpdate")
    @ResponseBody
    public Result homeUpdate(@RequestBody User user){

        Boolean flag = userService.Homeupdate(user);

        return new Result(flag ? Code.UPDATE_OK:Code.UPDATE_ERR,flag);    }

    @RequestMapping("/loadUser")
    @ResponseBody
    public Result loadUser(HttpSession session){
        User user = (User) session.getAttribute("user");
        return new Result(Code.GET_OK,user);
    }


}
